package co.edu.usbcali.sisgpim.dataaccess.dao;

import co.edu.usbcali.sisgpim.dataaccess.sessionFactory.HibernateSessionFactory;
import co.edu.usbcali.sisgpim.modelo.Usuarios;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.criterion.Example;

import java.math.BigDecimal;
import java.math.BigInteger;

import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * A data access object (DAO) providing persistence and search support for
 * Usuarios entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 *
 * @author Zathura Code Generator http://code.google.com/p/zathura
 *
 */
public class UsuariosDAO implements IUsuariosDAO {
    private static final Log log = LogFactory.getLog(UsuariosDAO.class);

    // property constants
    //public static final String  APELLIDOS = "apellidos";
    public static final String APELLIDOS = "apellidos";

    //public static final boolean  BLOQUEADO = "bloqueado";
    public static final String BLOQUEADO = "bloqueado";

    //public static final Integer  CODIGO = "codigo";
    public static final String CODIGO = "codigo";

    //public static final String  CORREOELECTRONICO = "correoElectronico";
    public static final String CORREOELECTRONICO = "correoElectronico";

    //public static final Date  FECHADESBLOQUEO = "fechaDesbloqueo";
    public static final String FECHADESBLOQUEO = "fechaDesbloqueo";

    //public static final Date  FECHANACIMIENTO = "fechaNacimiento";
    public static final String FECHANACIMIENTO = "fechaNacimiento";

    //public static final String  NOMBRES = "nombres";
    public static final String NOMBRES = "nombres";

    //public static final String  TELEFONO = "telefono";
    public static final String TELEFONO = "telefono";

    private Session getSession() {
        return HibernateSessionFactory.getSession();
    }

    /**
    *
    * @param Instance
    *            Usuarios Instance to persist
    * @throws RuntimeException
    *             when the operation fails
    */
    public void save(Usuarios instance) {
        log.debug("saving Usuarios instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    /**
    * @param Instance
    *            Usuarios Instance to delete
    * @throws RuntimeException
    *             when the operation fails
    */
    public void delete(Usuarios instance) {
        log.debug("deleting Usuarios instance");

        try {
            getSession().delete(instance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
    *
    * @param Instance
    *            Usuarios Instance to update
    * @throws RuntimeException
    *             when the operation fails
    */
    public void update(Usuarios instance) {
        log.debug("updating Usuarios instance");

        try {
            getSession().update(instance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }

    public Usuarios findById(Integer id) {
        log.debug("finding Usuarios instance with id: " + id);

        try {
            Usuarios instance = (Usuarios) getSession().get(Usuarios.class, id);

            return instance;
        } catch (RuntimeException re) {
            log.error("finding Usuarios failed", re);
            throw re;
        }
    }

    public List<Usuarios> findByExample(Usuarios instance) {
        log.debug("finding Usuarios instance by example");

        try {
            List results = getSession().createCriteria("Usuarios")
                               .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: " +
                results.size());

            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    /**
    * Find all  Usuarios entities with a specific property value.
    *
    * @param value
    *            the property value to match
    * @param propertyName
    *            the property to search in the instance
    * @return List< Usuarios> found by query
        */
    public List<Usuarios> findByProperty(String propertyName, Object value) {
        log.debug("finding Usuarios instance with property: " + propertyName +
            ", value: " + value);

        try {
            String queryString = "from Usuarios as model where model." +
                propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List<Usuarios> findByApellidos(Object apellidos) {
        return findByProperty(APELLIDOS, apellidos);
    }

    public List<Usuarios> findByBloqueado(Object bloqueado) {
        return findByProperty(BLOQUEADO, bloqueado);
    }

    public List<Usuarios> findByCodigo(Object codigo) {
        return findByProperty(CODIGO, codigo);
    }

    public List<Usuarios> findByCorreoElectronico(Object correoElectronico) {
        return findByProperty(CORREOELECTRONICO, correoElectronico);
    }

    public List<Usuarios> findByFechaDesbloqueo(Object fechaDesbloqueo) {
        return findByProperty(FECHADESBLOQUEO, fechaDesbloqueo);
    }

    public List<Usuarios> findByFechaNacimiento(Object fechaNacimiento) {
        return findByProperty(FECHANACIMIENTO, fechaNacimiento);
    }

    public List<Usuarios> findByNombres(Object nombres) {
        return findByProperty(NOMBRES, nombres);
    }

    public List<Usuarios> findByTelefono(Object telefono) {
        return findByProperty(TELEFONO, telefono);
    }

    /**
    * Find all Usuarios entities.
    *
    * @return List<Usuarios> all Usuarios instances
    */
    public List<Usuarios> findAll() {
        log.debug("finding all Usuarios instances");

        try {
            String queryString = "from Usuarios";
        	//String queryString = "select * from sisgpim.usuarios";
            Query queryObject = getSession().createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public List<Usuarios> findByCriteria(String whereCondition) {
        log.debug("finding Usuarios " + whereCondition);

        try {
            String where = ((whereCondition == null) ||
                (whereCondition.length() == 0)) ? "" : ("where " +
                whereCondition);
            final String queryString = "select model from Usuarios model " +
                where;
            Query query = getSession().createQuery(queryString);
            List<Usuarios> entitiesList = query.list();

            return entitiesList;
        } catch (RuntimeException re) {
            log.error("find By Criteria in Usuarios failed", re);
            throw re;
        }
    }

    public List<Usuarios> findPageUsuarios(String sortColumnName,
        boolean sortAscending, int startRow, int maxResults) {
        log.debug("finding Usuarios findPageUsuarios");

        if ((sortColumnName != null) && (sortColumnName.length() > 0)) {
            try {
                String queryString = "select model from Usuarios model order by model." +
                    sortColumnName + " " + (sortAscending ? "asc" : "desc");

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        } else {
            try {
                String queryString = "select model from Usuarios model";

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        }
    }

    public Long findTotalNumberUsuarios() {
        log.debug("finding Usuarios count");

        try {
            //String queryString = "select count(*) from Usuarios model";
            String queryString = "select count(*) from sisgpim.usuarios";
            Query queryObject = getSession().createSQLQuery(queryString);
            BigInteger num = (BigInteger) queryObject.uniqueResult();
            
            return new Long(num.longValue());
        } catch (RuntimeException re) {
            throw re;
        }
    }
}
